import {  Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, Not } from 'typeorm';

import { Dish } from '../entity/dish.entity';

@Provide()
export class DishService {
    @InjectEntityModel(Dish)
    dishModel: Repository<Dish>;

    /**
     * 创建菜品
     */
    async create(dish: Partial<Dish>): Promise<Dish> {
        // 检查菜品名称是否存在
        const existDish = await this.dishModel.findOne({
            where: { dishName: dish.dishName }
        });
        if (existDish) {
            throw new Error('菜品名称已存在');
        }

        const newDish = this.dishModel.create(dish);
        return await this.dishModel.save(newDish);
    }

    /**
     * 更新菜品
     */
    async update(id: number, dish: Partial<Dish>): Promise<boolean> {
        if (dish.dishName) {
            const existDish = await this.dishModel.findOne({
                where: { dishName: dish.dishName, id: Not(id) }
            });
            if (existDish) {
                throw new Error('菜品名称已存在');
            }
        }

        const result = await this.dishModel.update(id, dish);
        return result.affected > 0;
    }

    /**
     * 删除菜品（软删除）
     */
    async delete(id: number): Promise<boolean> {
        const result = await this.dishModel.update(id, {
            delFlag: 1,
            updateTime: new Date()
        });
        return result.affected > 0;
    }

    /**
     * 获取菜品信息
     */
    async getInfo(id: number): Promise<Dish> {
        return await this.dishModel.findOne({
            where: { id, delFlag: 0 }
        });
    }

    /**
     * 获取菜品列表
     */
    async getList(params: {
        page?: number;
        pageSize?: number;
        dishName?: string;
        status?: number;
        categoryId?: number;
    }): Promise<[Dish[], number]> {
        const { page = 1, pageSize = 10, dishName, status, categoryId } = params;

        const queryBuilder = this.dishModel.createQueryBuilder('dish')
            .where('dish.delFlag = :delFlag', { delFlag: 0 });

        if (dishName) {
            queryBuilder.andWhere('dish.dishName LIKE :dishName', {
                dishName: `%${dishName}%`
            });
        }

        if (status !== undefined) {
            queryBuilder.andWhere('dish.status = :status', { status });
        }

        if (categoryId) {
            queryBuilder.andWhere('dish.categoryId = :categoryId', { categoryId });
        }

        return await queryBuilder
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount();
    }
}